import { defineStore } from "pinia";
import { ref } from "vue";
import type { MenuItemType } from "@/types/user/index";

export const useTabsStore = defineStore("tabs", () => {
  const tabs = ref<MenuItemType[]>([]);
  //设置高亮数据，用于双向绑定和路由跳转
  let activeTab = ref({ name: "", url: "" });
  //判断是否重复添加标签
  const addTab = (name: string, url: string, icon: string) => {
    if (
      !tabs.value.some((tab) => {
        return tab.url === url;
      })
    ) {
      tabs.value.push({ name, url, icon });
    }
  };

  //设置高亮
  const setActiveTab = (name: string, url: string) => {
    activeTab.value = { name, url };
  };

  //删除标签
  const removeTab = (name: string) => {
    if (activeTab.value.name === name) {
      const tabIndex = tabs.value.findIndex((tab) => {
        return tab.name === name;
      });
      if (tabIndex != 0) {
        activeTab.value = tabs.value[tabIndex - 1];
      } else {
        return;
      }
    }

    tabs.value = tabs.value.filter((tab) => {
      return tab.name !== name;
    });
  };

  return { tabs, addTab, activeTab, setActiveTab, removeTab };
});
